﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Ajax;
using VideoClassLibrary.BusinessLogicLayer;
using VideoClassLibrary.Extension;
using VideoClassLibrary.Model;

/// <summary>
/// Summary description for AjaxMethodHelper
/// </summary>
public class AjaxMethodHelper:AdminUserBase
{
    public HttpContext Context { get; private set; }
    public string PostData { get; set; }
    public string StrValue { get; set; }

    public AjaxMethodHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public AjaxMethodHelper(HttpContext context)
    {
        Context = context;

        if (Context.Request.Form["strValue"] != null)
            StrValue = Context.Request.Form["strValue"];
        if (Context.Request.Form["PostData"] != null)
            PostData = Context.Request.Form["PostData"];
    }

    public  string CheckUser()
    {
        UserModule um=new UserModule();
       if(!um.IfNameExist(CurrentUser.SchoolID, PostData))
       {
           return "1";
       }
        return "-1";

    }

    public  string  SaveFormatTime()
    {
        var StartTime = PostData;
        var SendTime = StrValue;
        var Vsid = Context.Request.Form["Vsid"];
        var formatTime = StartTime + ";" + SendTime;
         
        int rtn = 0;
        ClassRoomModule ra = new ClassRoomModule();
        if (ra.ChkExsit(Convert.ToInt32(Vsid)) > 0)
        {
            rtn = 2;

        }
        else
        {
            rtn = ra.VideoFormat(Convert.ToInt32(Vsid), formatTime);
        }
        return rtn.ToString();

    }


    public  string  CheckSVR()
    {

        var SvrPort = this.PostData;
        var svrList = StrValue;
        ClassRoomModule ra = new ClassRoomModule();
        DataSet dataSet=ra.ChkSvrPort(SvrPort, svrList);
        if(dataSet.Tables[0].Rows.Count>0)
        {
            return "对不起，端口号" + PostData + "，被" + dataSet.Tables[0].Rows[0]["Vs_name"] + "学校的：" + dataSet.Tables[0].Rows[0]["VR_roomName"]+"教室占用！";

        }
        return "";
    }

    /// <summary>
    /// 保存多个学员
    /// </summary>
    /// <returns></returns>
    public  string  SaveUser()
    {
        UserModule um = new UserModule();
        int num = 0;
        List<V_user> dtos = this.PostData.FromJsonTo<List<V_user>>();
       
        int failCount = 0;
        int successCount = 0;
        List<ReturnResult> resultList = um.QuantityRegisterUser(dtos, this.SchoolID);
        ReturnResult result = null;
        for (int i = 0; i < resultList.Count; i++)
        {
            result = resultList[i];
            
            if (result.IsSuccess == true)
            {
                successCount += 1;
               
            }
            else if (result.ErrorMsg != "")
            {
               
                failCount += 1;
            }
            
        }
        if (successCount > 0 && failCount == 0)
        {
            return "Success";
        }
        //foreach (var vUser in dtos)
        //{
        //    vUser.create_time = DateTime.Now;
        //    vUser.update_time = DateTime.Now;
        //    vUser.IsAvailable = true;
        //    vUser.VU_Password = StringUtils.EncryptPassWord(vUser.VU_loginname, StringUtils.PassFormat.MD5);
        //    vUser.SchoolID = CurrentUser.SchoolID;
        //    num += um.AddUser(vUser);
        //}
        return num.ToString();

    }

    public string ChkCourse(string opType)
    {
        string className = Context.Request.Form["ClassName"];
        string classRoom = Context.Request.Form["classRoom"];
        string classTeacher = Context.Request.Form["classTeacher"];
        string classBeginTime = Context.Request.Form["classBeginTime"];
        string classEndTime = Context.Request.Form["classEndTime"];
        string classBeginDate = Context.Request.Form["ClassBeginDate"];
        string classEndDate = Context.Request.Form["classEndDate"];
        string classCourse=Context.Request.Form["classCourse"];
        string ID = Context.Request.Form["Id"];
        CourseListModule courseListModule=new CourseListModule();
     //   V_adminUser vAdminUser = (V_adminUser) HttpContext.Current.Session["currentAdminUser"];
        V_adminUser vAdminUser = CurrentUser;

        if (courseListModule.ChkCourse(className, classRoom, classTeacher, classBeginTime, classEndTime, classBeginDate, classEndDate, classCourse) > 0)
        {
            return "1";
        }
        V_courselist co = new V_courselist();
        co.SchoolID = vAdminUser.SchoolID;
        co.courseID = Convert.ToInt32(classCourse);
        co.RoomID = Convert.ToInt32(classRoom);
        co.TrainClassId = Convert.ToInt32(className);
        co.teacherID = Convert.ToInt32(classTeacher);
        co.VCL_EndDate = Convert.ToDateTime(classEndDate);
        co.VCL_EndTime = Convert.ToDateTime(classEndTime);
        co.VCL_startDate = Convert.ToDateTime(classBeginDate);
        co.VCL_startTime = Convert.ToDateTime(classBeginTime);
        if (("u").Equals(opType))
        {
            if (!string.IsNullOrEmpty(ID))
            {
                co.ID = Convert.ToInt32(ID);
                courseListModule.UpdateCourseList(co);
                return "success";
            }
        }
        if (("a").Equals(opType))
        {
            {
                if (courseListModule.AddCourseList(co) > 0)
                {
                    return "2";
                }
            }

            }
        return "-1";
    }

     public string  SaveCourses()
     {
         List<V_course> dtos = this.PostData.FromJsonTo<List<V_course>>();
         CourseModule courseListModule = new CourseModule();
         int result = 0;
         bool flg = false;
         if (dtos.Any(vCourse => vCourse.TrainClassID == 0))
         {
             return "False";
         }


         foreach (var vCourse in dtos)
         {
             vCourse.Create_time = DateTime.Now;
             vCourse.Update_time = DateTime.Now;
              result +=courseListModule.AddCourseModel(vCourse);
         }
         return result.ToString();
     }

    /// <summary>
    /// 获取验证码
    /// </summary>
    /// <returns>验证码</returns>
    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
    public String GetValidateCode()
    {
        return HttpContext.Current.Session["validateCode"] == null ? "" : HttpContext.Current.Session["validateCode"].ToString();
    }


    /// <summary>
    /// 检查用户名是否被占用
    /// </summary>
    /// <param name="loginName">待检查的用户名</param>
    /// <returns>被占用返回true,没被占用返回false</returns>
    [AjaxMethod]
    public bool IsExistsUser(String loginName)
    {
        UserModule userModule = new UserModule();
        return !userModule.CanRegistUser(loginName);
    }
    [AjaxMethod]
    public bool IsExistTrainClassId(string trainClassId)
    {
        return new TrainClassModule().IsTrainClassNum(trainClassId);
    }

    [AjaxMethod]
    public bool IsExistTrainClassIdBySchoolId(int schoolId, string trainClassId)
    {
        return new TrainClassModule().IsTrainClassNumBySchoolId(schoolId, trainClassId);
    }
}